<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-wms__purchase}">
      <div class="ba-operate-form">
        <el-form :model="dataForm" @keyup.enter.native="getDataList()" label-width="70px">
          <el-row :gutter="20">
            <el-col :md="6" :sm="6">
              <el-form-item label="主单编号">
                <el-input v-model="dataForm.purchaseNo" placeholder="精确匹配" maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <el-form-item label="砂芯图号">
                <el-input v-model="dataForm.spuNo" placeholder="精确匹配" maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <el-form-item label="需求站台">
                <el-input v-model="dataForm.stationNo" placeholder="模糊匹配" maxlength="20" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :md="6" :sm="6">
              <div class="right-handle-group">
                <el-button-group>
                  <el-button @click="getDataList()" type="primary">{{ $t('query') }}</el-button>
                  <el-button @click="getReset()">{{ $t("reset") }}</el-button>
                  <el-tooltip class="item" effect="dark" content="高级搜索" placement="top-start">
                    <el-button @click="advanced = !advanced" color="#dcdfe6" icon="el-icon-search" plain></el-button>
                  </el-tooltip>
                </el-button-group>
              </div>
            </el-col>
          </el-row>
          <el-collapse-transition>
            <div v-show="advanced">
              <el-row :gutter="20">
                <el-col :md="6" :sm="9">
                  <el-form-item label="主单状态">
                    <el-select v-model="dataForm.purchaseSt" placeholder="可选状态">
                      <el-option v-for="item in statusOption" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :md="8" :sm="12">
                  <el-form-item label="创建日期">
                    <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
                      range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                      :picker-options="pickerOptions">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-collapse-transition>
        </el-form>
      </div>
      <div class="ba-operate-button">
        <el-form :inline="true">
          <el-form-item>
            <el-button v-if="$hasPermission('wms:purchase:save')" type="primary" @click="addOrUpdateHandle()">{{
              $t("add")
            }}</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-if="$hasPermission('wms:purchase:done')" type="warning" @click="purchaseDone()">{{
              $t("forceDone")
            }}</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-if="$hasPermission('wms:purchase:delete')" type="danger" @click="purchaseCancel()">{{
              $t("delete")
            }}</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 主表内容 -->
      <el-table class="purchaseTable" v-loading="dataListLoading" :row-key="getRowKey" :data="dataList"
        :expand-row-keys="expands" border ref="Table" @select="selectChangeHandle" style="width: 100%"
        @expand-change="rowExpand">
        <el-table-column type="expand">
          <!-- 明细内容 -->
          <el-table :data="detailList" border style="width: 100%">
            <el-table-column prop="detailId" label="明细id" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="childHandle(scope.row)">{{
                  scope.row.detailId
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="detailSt" label="明细状态" align="center" min-width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.detailSt === 0">初始</el-tag>
                <el-tag v-else-if="scope.row.detailSt === 1" type="warning">收货中</el-tag>
                <el-tag v-else-if="scope.row.detailSt === 2" type="success">已完成</el-tag>
                <el-tag v-else-if="scope.row.detailSt === 4" type="warning">强制完成</el-tag>
                <el-tag v-else-if="scope.row.detailSt === 9" type="warning">废弃</el-tag>
                <el-tag v-else type="danger">未知状态</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="spuNo" label="砂芯图号" align="center" min-width="110"></el-table-column>
            <el-table-column prop="planQnty" label="计划量" align="center"></el-table-column>
            <el-table-column prop="bindQnty" label="绑定量" align="center"></el-table-column>
            <el-table-column prop="actlQnty" label="实收量" align="center"></el-table-column>

            <el-table-column prop="creatorName" label="创建用户" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createDate" label="创建日期" align="center" min-width="155"></el-table-column>
            <el-table-column prop="updaterName" label="更新用户" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="updateDate" label="更新日期" align="center" min-width="155"></el-table-column>
            <el-table-column prop="comments" label="备注" align="center" show-overflow-tooltip></el-table-column>
          </el-table>
        </el-table-column>
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="purchaseId" label="id" header-align="center" align="center" sortable></el-table-column>
        <el-table-column prop="purchaseSt" label="主单状态" header-align="center" align="center" min-width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.purchaseSt === 0">初始</el-tag>
            <el-tag v-else-if="scope.row.purchaseSt === 1" type="warning">收货中</el-tag>
            <el-tag v-else-if="scope.row.purchaseSt === 2" type="success">已完成</el-tag>
            <el-tag v-else-if="scope.row.purchaseSt === 4" type="warning">强制完成</el-tag>
            <el-tag v-else-if="scope.row.purchaseSt === 9" type="warning">废弃</el-tag>
            <el-tag v-else type="danger">未知状态</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="purchaseNo" label="单据编号" header-align="center" align="center" min-width="145" sortable>
        </el-table-column>
        <el-table-column prop="purchaseType" label="计划类型" header-align="center" align="center"></el-table-column>
        <el-table-column prop="spuNo" label="砂芯图号" header-align="center" align="center" min-width="135">
        </el-table-column>
        <el-table-column prop="lotNo" label="批次" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="amount" label="需求量" header-align="center" align="center"></el-table-column>
        <el-table-column prop="stationNo" label="上料站台" header-align="center" align="center" min-width="120">
        </el-table-column>

        <el-table-column prop="creatorName" label="创建用户" header-align="center" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="createDate" label="创建日期" header-align="center" align="center" min-width="155" sortable>
        </el-table-column>
        <el-table-column prop="updaterName" label="更新用户" header-align="center" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="updateDate" label="更新日期" header-align="center" align="center" min-width="155" sortable>
        </el-table-column>
        <el-table-column prop="comments" label="备注" header-align="center" align="center" show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    </div>
  </el-card>
</template>

<script>
import mixinViewModule from "@/mixins/view-module";
import AddOrUpdate from "./purchase-add-or-update";
import { addDynamicRoute } from "@/router";
export default {
  mixins: [mixinViewModule],
  data() {
    return {
      mixinViewModuleOptions: {
        getDataListURL: "/wms/purchase/page",
        getDataListIsPage: true,
        exportURL: "/wms/purchase/export",
      },
      dataForm: {
        purchaseId: '',
        purchaseNo: '',
        purchaseSt: '',
        stationNo: '',
        spuNo: '',
        startDate: '',
        endDate: '',
      },
      //日期范围
      dateRange: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "当天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0, 0, 0);

              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          }
        ]
      },
      advanced: false,
      statusOption: [],
      dictType: "purchase_status",
      routeTitle: "关联任务-入库",
      getRowKey(row) {
        return row.purchaseId;
      },
      expands: [],
      detailList: null,
    };
  },
  components: {
    AddOrUpdate,
  },
  created() {
    this.getPurchaseStatusList();
  },
  methods: {
    //0.重置搜索框
    getReset() {
      this.dataForm = this.$options.data().dataForm;
      this.dateRange = this.$options.data().dateRange;
    },
    //1.明细展开
    rowExpand(row, expandedRows) {
      this.expands = [];
      if (expandedRows.length > 0) {
        row ? this.expands.push(row.purchaseId) : "";
        this.purchaseNo = row.purchaseNo;
        this.detailList = row.purchaseDetailList;
      }
    },
    // 2.单选(确认出库单据id)
    selectChangeHandle(selection, row) {
      this.dataForm.purchaseId = ''; //每次单选都重置id

      if (selection.length > 1) {
        this.$refs.Table.clearSelection()
        this.$refs.Table.toggleRowSelection(row)
      }
      if (selection.length != 0) {
        //只有当真正选中了目标主单才获取id
        this.dataForm.purchaseId = row.purchaseId;
      }
    },
    // 3.任务跳转
    childHandle(row) {
      // 路由参数
      const routeParams = {
        routeName: `${this.$route.name}__${row.detailId}`,
        title: `${this.routeTitle} - ${row.detailId}`,
        path: "wms/detail-task",
        params: {
          mtNo: this.purchaseNo,
          dtId: row.detailId,
        },
      };
      // 动态路由
      addDynamicRoute(routeParams, this.$router);
    },
    //4.获取单据状态描述
    getPurchaseStatusList() {
      this.$http
        .get(`/sys/dict/type/list`, {
          params: {
            dictType: this.dictType,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.statusOption = res.data;
        }).catch(() => { });
    },
    //收货单强制完成
    purchaseDone() {
      if (!this.dataForm.purchaseId) {
        return this.$message({
          message: this.$t("prompt.forceDone"),
          type: "warning",
          duration: 1000,
        });
      }

      this.$confirm(
        this.$t("prompt.info", { handle: this.$t("forceDone") }),
        this.$t("prompt.title"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(() => {
          this.$http
            .post(`/wms/purchase/${this.dataForm.purchaseId}`)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: res.msg,
                type: "success",
                duration: 500,
                onClose: () => {
                  this.query();
                },
              });
            })
            .catch(() => { });
        })
        .catch(() => { });
    },
    //收货单取消
    purchaseCancel() {
      if (!this.dataForm.purchaseId) {
        return this.$message({
          message: this.$t("prompt.deleteBatch"),
          type: "warning",
          duration: 1000,
        });
      }

      this.$confirm(
        this.$t("prompt.info", { handle: this.$t("delete") }),
        this.$t("prompt.title"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(() => {
          this.$http
            .delete(`/wms/purchase/${this.dataForm.purchaseId}`)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: res.msg,
                type: "success",
                duration: 500,
                onClose: () => {
                  this.query();
                },
              });
            })
            .catch(() => { });
        })
        .catch(() => { });
    },
  }
};
</script>

<style>
/* 隐藏表头的全选框 */
.purchaseTable thead .el-table-column--selection .cell {
  display: none;
}

.el-row {
  margin-bottom: 0px;
}

.right-handle-group {
  float: right;
}
</style>
